/**
 * 0. Project	: com.dnbns.bodywater.adapter 프로젝트
 *
 * 1. FileName	: AlarmAdapter.java
 * 2. Package	: com.dnbns.bodywater.adapter
 * 3. 작성자		: 윤화현
 * 4. 작성일		: 2013. 12. 31. 오전 10:07:16
 * 5. Comment	: 
 */

package com.dnbns.bodywater.adapter;

import java.util.ArrayList;

import org.json.JSONException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.dnbns.bodywater.R;
import com.dnbns.bodywater.bean.AlarmBean;
import com.dnbns.common.AlarmSchedule;
import com.dnbns.lib.CodeUtil;

public class AlarmAdapter extends ArrayAdapter<AlarmBean> {
	private static final int VIEW_RESOURCE_ID = R.layout.row_alarm;
	private Activity mActivity;
	private LayoutInflater mInflater;
	
	public AlarmAdapter(Activity mActivity, ArrayList<AlarmBean> list){
		super(mActivity, VIEW_RESOURCE_ID, list);
		this.mActivity = mActivity;
		mInflater = (LayoutInflater)mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
    
	@Override
	public View getView(final int position, View convertView, ViewGroup parent){
		View view = convertView;
		if(view == null){
			view = mInflater.inflate(VIEW_RESOURCE_ID, null); 
		}

		final AlarmBean item = getItem(position);
    	if (item != null) {
    		TextView date = (TextView)view.findViewById(R.id.date);
    		date.setText(item.getHour()+":"+item.getMinute());

    		ImageView delete = (ImageView)view.findViewById(R.id.delete);
    		delete.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					AlertDialog.Builder ab = new AlertDialog.Builder(mActivity);
					ab.setTitle("삭제");
					ab.setMessage("삭제하시겠습니까?");
					ab.setPositiveButton("확인", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							try {
								CodeUtil.getInstance(mActivity).deleteCode2(2000, item.getIdx()+"");
								remove(item);
								AlarmSchedule.getInstance(mActivity).deleteAlarmSchedule(item.getIdx());
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							notifyDataSetInvalidated();
							dialog.dismiss();
						}
					});
					ab.setNegativeButton("취소", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();
						}
					});
					ab.show();
				}
			});
    	}
		return view;
	}
}